import 'dart:collection';
import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:group_button/group_button.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/life/CartOrder.dart';
import 'package:shop/shop/life/GoodsDetail.dart';

//店铺详情
class MerchantPage extends StatefulWidget {
  String merchantTypeId;  //店铺类型ID
  String merchantId;      //店铺ID
  MerchantPage({Key key, this.title, this.merchantTypeId, this.merchantId}) : super(key: key);

  final String title;

  @override
  _MerchantPage createState() => _MerchantPage(merchantTypeId,merchantId);
}

class _MerchantPage extends State<MerchantPage> {
  List goodsTypeList=[];    //一级类别的列表
  List goodsList = [];      //商品列表
  var params = [];          //规格下标
  var names = [];           //选中的规格
  var panduan = [];         //判断规格是否选重复
  List cartList = [];       //购物车列表
  int cartsize=0;
  String guiges = "";       //字符串规格
  String guigexiabiao = ""; //字符串规格下标
  int index=0;

  int xiabiao=0;

  String s="";              //用户选择的规格
  num zongjia=0.0;          //总价格
  num zongdabaofei=0.0;     //总打包费
  num guigejia=0.0;         //规格价格
  String zongjiage;         //保留两位小数显示的总价格
  dynamic funCb;

  var merchant = {};        //商家信息
  String merchantTypeId;    //店铺类型ID
  String merchantId;        //店铺ID
  String merchantName="";   //店铺名称
  double qisongMoney=0.0;   //店铺起送金额
  bool guanzhu = false;     //用户是否关注店铺
  int sellNum = 0;          //店铺总销量
  String phonenumber="";    //联系电话
  int yingyeStatus=0;       //营业状态
  String icon="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.mp.itc.cn%2Fupload%2F20170215%2F0edb3abc2de44179af2020ce1f05894a_th.jpg&refer=http%3A%2F%2Fimg.mp.itc.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1632910571&t=404554f48d58eaa5e975b7ca828cb69b";//店铺图片
  String userId;            //用户ID
  var guigeList;
  _MerchantPage(merchantTypeId,merchantId){
    this.merchantId=merchantId;
    this.merchantTypeId=merchantTypeId;
    _loading();
  }

  Future<void> _loading() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    userId = prefs.getString("userId");
    if(userId==null || userId==""){
      userId = "";
    }
    //查询一级类别
    var x = await HttpUtil().get("/waimai/mGoodsType/selectMGoodsType?mType=${merchantTypeId}&mId=${merchantId}&userId="+userId);
    if(x['code']==200){
      goodsTypeList=x['data']['mGoodsTypes'];
      cartList=x['data']['cats'];
      guanzhu = x['data']['guanzhu'];
      for(int i=0;i<cartList.length;i++){
        cartsize+=cartList[i]['scatNum'];
      }
      zongjia = double.parse(x['msg']);
      if(zongjia > 0){
        zongjiage = zongjia.toStringAsFixed(2);
      }else{
        zongjiage = "0.00";
      }
      zongdabaofei = x['data']['zongdabaofei'];
      if(x['data']['mGoodsTypes'].length>0){
        goodsList = x['data']['mGoodsTypes'][0]['mgoodsList'];
      }
      for(int a=0;a<goodsTypeList.length;a++){
        for(int b=0;b<goodsTypeList[a]["mgoodsList"].length;b++){
          sellNum=sellNum+goodsTypeList[a]["mgoodsList"][b]['gsellnum'];
        }
      }
    }else{
      Fluttertoast.showToast(
          msg: "未找到商品类别",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black45,
          textColor: Colors.white,
          fontSize: 16.0
      );
    }
    //查询商家详情
    var y = await HttpUtil().get("/waimai/merchant/getByMerchantID?mId=${merchantId}");
    if(y['code']==200){
      merchant = y['data'];
      merchantName = merchant['mname'];
      qisongMoney = merchant['qisongMoney'] as double;
      icon = Config.getInstance().getHost()+y['data']['picture'];
      yingyeStatus = y['data']['yingyeStatus'];
    }
    if(mounted){
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context , width: 464 , height: 820) ;
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(1),
        child: AppBar(

        ),
      ),
      body:Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.fromLTRB(5, 10, 5, 0),
            child:Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Container(
                      height: ScreenUtil().setHeight(80),
                      width: ScreenUtil().setWidth(80),
                      decoration: BoxDecoration(
                        borderRadius:BorderRadius.circular(15),
                        image: new DecorationImage(
                          image: new NetworkImage(icon),
                          //这里是从assets静态文件中获取的，也可以new NetworkImage(）从网络上获取
                          // centerSlice: new Rect.fromLTRB(270.0, 180.0, 1360.0, 730.0),
                        ),
                      ),
                    ),
                    SizedBox(width: 15,),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          width: ScreenUtil().setWidth(320),
                          height: ScreenUtil().setHeight(40),
                          child: Row(
                            children: [
                              Expanded(child: Text(merchantName,style: TextStyle(fontWeight: FontWeight.bold,fontSize: 22),),),
                              SizedBox(width: 20,),
                              GestureDetector(child: Container(
                                child: guanzhu ? Icon(Icons.star,color: Colors.orange,) : Icon(Icons.star_border),
                              ),onTap: () async {
                                var map = new HashMap<String,dynamic>();
                                map['mid']=merchantId;map['type']=0;map['userId']=userId;map['mtypeId']=merchantTypeId;
                                Response response = await HttpUtil().post("waimai/mCollect/collect",map);
                                var x = json.decode(response.toString());
                                if(x['code']==200){
                                  if(guanzhu){
                                    guanzhu = false;
                                  }else{
                                    guanzhu = true;
                                  }
                                }
                                Fluttertoast.showToast(
                                    msg: x['msg'],
                                    toastLength: Toast.LENGTH_SHORT,
                                    gravity: ToastGravity.BOTTOM,
                                    timeInSecForIosWeb: 1,
                                    backgroundColor: Colors.black45,
                                    textColor: Colors.white,
                                    fontSize: 16.0
                                );
                                setState(() {

                                });
                              },)
                            ],
                          ),
                        ),
                        Text("总销量"+sellNum.toString()+" 配送约30分钟"),
                      ],
                    )
                  ],
                ),
                Row(
                  children: [
                    Container(
                        padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                        decoration: BoxDecoration(
                            border: Border(bottom: BorderSide(width: 1,color: Colors.orange))
                        ),
                        child: qisongMoney>=0 ? Text("下单",style: TextStyle(fontSize: 16,fontWeight: FontWeight.w600),) : Text("")
                    ),
                    Container(
                      padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
                      child: Text(yingyeStatus==0 ? "休息中" : "营业中" ,style: TextStyle(color: yingyeStatus==0?Colors.grey:Colors.green),),
                    ),
                    Row(
                      children: [
                        Icon(Icons.call),
                        Text(merchant['tousuPhone']!=null ? merchant['tousuPhone'] : "",)
                      ],
                    )
                  ],
                )
              ],
            )
          ),
          Expanded(
            child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SingleChildScrollView(
                child: Column(
                  children: [
                    // 得到商品类型
                    _getGoodsType(),
                  ],
                ),
              ),
              SingleChildScrollView(
                child: Column(
                  // crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                      decoration: BoxDecoration(color: Colors.white),
                      padding: EdgeInsets.all(10),
                      width: ScreenUtil().setWidth(350),
                      child: Wrap(
                        // 这里是二级分类
                        children: [
                          Column(
                            children: [
                              // Container(
                              //   height: ScreenUtil().setHeight(40),
                              //   child:Row(children: [goodsTypeList.length>0 ? Text(goodsTypeList[xiabiao]['name']) : Text("")])
                              // ),  // 二级分类名称
                              //得商品
                              _getGoods(),
                          ],
                        )],
                      ),
                    )
                  ],
                ),
              )
            ],
          )),
          Container(
            margin: EdgeInsets.symmetric(horizontal: 10,vertical: 5),
            padding: EdgeInsets.symmetric(vertical: 5),
            decoration:  new BoxDecoration(
              //背景
              color: Colors.black,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(10)),
              //设置四周边框
              border: new Border.all(width: 1, color: Colors.black),
            ),
            child: Center(
              child: Container(
                width: ScreenUtil().setWidth(450),
                decoration: BoxDecoration(
                  // borderRadius: BorderRadius.all(Radius.circular(30)) ,
                  // border: Border.all(color: Colors.black , width: 1) ,
                  color: Colors.black,
                ),
                margin: EdgeInsets.fromLTRB(0, 0, 0, 5),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    GestureDetector(
                      child:Row(
                        children: [
                          Icon(Icons.shopping_cart,color: Colors.yellow,size: 35,),
                          Container(
                            margin: EdgeInsets.fromLTRB(0, 0, 0, 20),
                            padding: EdgeInsets.all(2),
                            decoration: BoxDecoration(
                              color: Colors.red,
                              borderRadius:BorderRadius.circular(10),
                            ),
                            child: Row(
                              children: [
                                Text(cartsize.toString(),style: TextStyle(color: Colors.white,fontSize: 13),)
                              ],
                            ),
                          )
                        ],
                      ),onTap: (){
                        cartsize==0 ?
                        Fluttertoast.showToast(
                            msg: "您还未加入商品",
                            toastLength: Toast.LENGTH_SHORT,
                            gravity: ToastGravity.BOTTOM,
                            timeInSecForIosWeb: 1,
                            backgroundColor: Colors.black45,
                            textColor: Colors.white,
                            fontSize: 16.0
                        )
                            :
                      showDialog<Null>(//展示购物车的窗口
                        context: context,
                        barrierDismissible: true, // 点击窗口外部是否自动关闭
                        builder: (BuildContext context) {
                          return StatefulBuilder(
                            builder: (context1,state){
                            funCb = state;
                              return new AlertDialog(
                                title: new Text("购物车"),
                                content: new SingleChildScrollView(
                                  child: new ListBody(
                                    children: <Widget>[
                                      showCart(cartList,state,context)
                                    ],
                                  ),
                                ),
                              );
                            },
                          );
                        },
                      ).then((val) {
                      });
                    },
                    ),
                    Container(
                      width: ScreenUtil().setWidth(150),
                      margin: EdgeInsets.fromLTRB(0, 0, 50, 0),
                      child: Text("￥$zongjiage",style: TextStyle(color: Colors.white,fontSize: 20),),
                    ),
                    GestureDetector(
                      child: Container(
                        padding: EdgeInsets.symmetric(vertical: 10,horizontal: 20),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(30)) ,
                          border: Border.all(color: Colors.yellow , width: 1) ,
                          color: Colors.yellow,
                        ),
                        child: Text("去结算",style: TextStyle(color: Colors.black),),
                      ),
                      onTap: () async {
                        if(cartsize>0){
                          //跳订单页面
                          // MyRoute.push(CartOrder(orRemark: "",cartList: cartList,merchantName: merchant['mname'],dabaofei: zongdabaofei,zongjia: zongjiage,cartsize: cartsize,merchantId: merchantId,));
                          var value = await MyRoute.push(CartOrder(orRemark: "",cartList: cartList,merchantName: merchant['mname'],dabaofei: zongdabaofei,zongjia: zongjiage,cartsize: cartsize,merchantId: merchantId,));
                          if(value==1){
                            for(int x=0;x<cartList.length;x++){
                              cartList.removeAt(x);
                            }
                            for(int y=0;y<goodsList.length;y++){
                              goodsList[y]["catNum"]=0;
                            }
                            zongdabaofei=0;
                            zongjia=0;
                            setState(() {

                            });
                          }
                        }else{
                          Fluttertoast.showToast(
                              msg: "请先选择商品",
                              toastLength: Toast.LENGTH_SHORT,
                              gravity: ToastGravity.BOTTOM,
                              timeInSecForIosWeb: 1,
                              backgroundColor: Colors.black45,
                              textColor: Colors.white,
                              fontSize: 16.0
                          );
                        }
                      },
                    )
                  ],),
              ),
            ),
          )
        ],),
    );
  }

  //获取店铺商品类别
  Widget _getGoodsType(){
    List<Widget> x = [];
    // 遍历商品类型
    for(int i=0;i<goodsTypeList.length;i++){
      x.add(
          GestureDetector(child: Container(
            alignment: Alignment.center,
            decoration: BoxDecoration(
                color: xiabiao==i ? Colors.white : null
            ),
            child: GestureDetector(
              child: Row(
                children: [
                  Expanded(child: Center(child: Text(goodsTypeList[i]['name'],style: TextStyle(fontSize: 17,color: xiabiao==i ? Colors.black : Colors.black38,fontWeight: FontWeight.w500))))
                ],
              ),behavior: HitTestBehavior.opaque,
            ),width: 100,padding: EdgeInsets.fromLTRB(0,15,0,15),
            // ),width: 90,padding: EdgeInsets.symmetric(vertical: 10),
          ),onTap: (){
            xiabiao=i;
            goodsList=goodsTypeList[i]['mgoodsList'];
            setState(() {

            });
          },)
      );
    }
    return Container(
      width: ScreenUtil().setWidth(110),
      // height: ScreenUtil.screenHeight,
      decoration: new BoxDecoration(
        // color: Colors.black12,
      ),
      child: Column(children: x),
    ) ;
  }

  //解析购物车商品的规格
  String getGuigeString(val,params){
    List list=json.decode(val);
    List param=json.decode(params);
    int size=param.length;
    String str='';
    for(int i=0;i<size;i++){
      String value=list[i]['value'];
      var array=value.split('-');
      str+=list[i]['name']+":"+array[param[i]]+" ";
    }
    return str;
  }

  //子窗口显示购物车
  Widget showCart(list,state,context){
    List<Widget> col = [];
    for(int i=0;i<list.length;i++){
      col.add(
        Container(
          margin: EdgeInsets.only(left: 0, top: 5),
          //设置 child 居中
          alignment: Alignment(0, 0),
          height: ScreenUtil().setHeight(120),
          width: ScreenUtil().setWidth(300),
          //边框设置
          decoration: BoxDecoration(
            border:Border(bottom:BorderSide(width: 1,color: Colors.grey)),
          ),
          child: Row(
            children: [
              CachedNetworkImage(imageUrl: Config.getInstance().getHost()+list[i]['mgoods']['gimages'],width: 70,height: 70,),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: ScreenUtil().setWidth(150),
                    height: ScreenUtil().setHeight(30),
                    child: Row(
                      children: [
                        Expanded(child: Text(list[i]['mgoods']['gname']),),
                      ],
                    ),
                  ),
                  Container(
                    width: ScreenUtil().setWidth(150),
                    height: ScreenUtil().setHeight(50),
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            list[i]['guiges']==null ? "" : getGuigeString(list[i]['mgoods']['guige'],list[i]['guigeparams']),
                            style: TextStyle(fontSize: 10),
                          ),
                        )
                      ],
                    ),
                  ),
                  Row(
                    children: [
                      Container(
                        width: ScreenUtil().setWidth(70),
                        child: Row(
                          children: [
                            Text("￥",style: TextStyle(fontSize: 12,color: Colors.red)),
                            Text(list[i]['money'].toString(),style: TextStyle(fontSize: 15,color: Colors.red))
                          ],
                        ),
                      ),
                      SizedBox(width: ScreenUtil().setWidth(50),),
                      Row(
                        children: [
                          GestureDetector(
                            child: Container(
                              decoration:  new BoxDecoration(
                                //背景
                                color: Colors.white,
                                //设置四周圆角 角度
                                borderRadius: BorderRadius.all(Radius.circular(4.0)),
                                //设置四周边框
                                border: new Border.all(width: 1, color: Colors.orangeAccent),
                              ),
                              width: 15,
                              height: 20,
                              child: Center(
                                child: Text("-"),
                              ),
                              padding: EdgeInsets.fromLTRB(1, 0, 0, 1),
                            ),
                            onTap: () async {
                              List gList= [];
                              for(int i=0;i<goodsTypeList.length;i++){
                                var list= goodsTypeList[i]['mgoodsList'];
                                for(int j=0;j<list.length;j++){
                                  gList.add(list[j]);
                                }
                              }
                              if(list[i]['scatNum']>0){
                                for(int j=0;j<gList.length;j++){
                                  if(list[i]['userId']==userId && list[i]['mgid']==gList[j]['id']){
                                    var x = await HttpUtil().get("/waimai/mShopCat/gaiNum?scatId=${list[i]['id']}&type=1");
                                    if(x['code']==200){
                                      zongjia = zongjia-gList[j]['gprice']-gList[j]['gdabaofei'];
                                      zongdabaofei = zongdabaofei-gList[j]['gdabaofei'];
                                      zongjiage = zongjia.toStringAsFixed(2);
                                      cartsize--;
                                      gList[j]['catNum']--;
                                      list[i]['scatNum']--;
                                      if(list[i]['scatNum']<=0){
                                        cartList.removeAt(i);
                                      }
                                    }
                                    state(() {

                                    });
                                    setState(() {

                                    });
                                    if(cartsize<=0){
                                      Navigator.pop(context);
                                    }
                                    break;
                                  }
                                }
                              }
                            },
                          ),
                          SizedBox(width: ScreenUtil().setWidth(5),),
                          Container(
                            width: 25,
                            child: Center(
                              child:Text(list[i]['scatNum'].toString()),
                            ),
                          ),
                          SizedBox(width: 6,),
                          GestureDetector(
                            child: Container(
                              decoration:  new BoxDecoration(
                                //背景
                                color: Colors.orangeAccent,
                                //设置四周圆角 角度
                                borderRadius: BorderRadius.all(Radius.circular(4.0)),
                                //设置四周边框
                                border: new Border.all(width: 1, color: Colors.orangeAccent),
                              ),
                              width: 15,
                              height: 20,
                              child: Center(
                                child: Text("+"),
                              ),
                              padding: EdgeInsets.fromLTRB(1, 0, 0, 1),
                            ),
                            onTap: () async {
                              List gList= [];
                              for(int i=0;i<goodsTypeList.length;i++){
                                var list= goodsTypeList[i]['mgoodsList'];
                                for(int j=0;j<list.length;j++){
                                  gList.add(list[j]);
                                }
                              }
                              if(list[i]['scatNum']>0){
                                for(int j=0;j<gList.length;j++){
                                  if(list[i]['userId']==userId && list[i]['mgid']==gList[j]['id']){
                                    var x = await HttpUtil().get("/waimai/mShopCat/gaiNum?scatId=${list[i]['id']}&type=2");
                                    if(x['code']==200){
                                      zongjia = zongjia+gList[j]['gprice']+gList[j]['gdabaofei'];
                                      zongdabaofei = zongdabaofei+gList[j]['gdabaofei'];
                                      zongjiage = zongjia.toStringAsFixed(2);
                                      cartsize++;
                                      gList[j]['catNum']++;
                                      list[i]['scatNum']++;
                                    }
                                    state(() {

                                    });
                                    setState(() {

                                    });
                                    break;
                                  }
                                }
                              }
                            },
                          ),
                        ],
                      )
                    ],
                  )
                ],
              )
            ],
          ),
        )
      );
    }
    return Column(
      children: col
    );
  }

  //展示类别商品
  Widget _getGoods(){
    List<Widget> x = [];
    // 测试用的
    for(int i=0;i<goodsList.length;i++){
      x.add(InkWell(
        child:Container(
          margin: EdgeInsetsDirectional.only(bottom: 20),
          child:Row(
            children: [
              CachedNetworkImage(imageUrl: Config.getInstance().getHost()+goodsList[i]['gimages'],width: ScreenUtil().setWidth(110),height: ScreenUtil().setWidth(110),),
              SizedBox(width: 10,),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: ScreenUtil().setWidth(200),
                    margin: EdgeInsetsDirectional.only(top: 0),
                    child: Row(
                      children: [
                        Expanded(child: Text(goodsList[i]['gname'],maxLines:2, overflow:TextOverflow.ellipsis,style: TextStyle(fontSize: 20),),),
                      ],
                    ),
                  ),
                  Container(
                    width: ScreenUtil().setWidth(200),
                    margin: EdgeInsetsDirectional.only(top: 0),
                    child: Row(
                      children: [
                        Expanded(child: Text(goodsList[i]['jianjie'],maxLines:2,
                          overflow:TextOverflow.ellipsis, style: TextStyle(color: Colors.grey,fontSize: 14),),),
                      ],
                    ),
                  ),
                  Container(
                    width: ScreenUtil().setWidth(200),
                    margin: EdgeInsetsDirectional.only(bottom: 10),
                    child: Row(
                      children: [
                        Expanded(child: Text("销量："+goodsList[i]['gsellnum'].toString(),style: TextStyle(color: Colors.grey,fontSize: 14),),),
                      ],
                    ),
                  ),
                  Row(
                    children: [
                      Container(
                        width: ScreenUtil().setWidth(90),
                        child: Row(
                          children: [
                            Text("￥",style: TextStyle(fontSize: 12,color: Colors.red),),
                            Text("${goodsList[i]['gprice']}",style: TextStyle(fontSize: 16,color: Colors.red))
                          ],
                        ),
                      ),
                      SizedBox(width: ScreenUtil().setWidth(40),),
                      goodsList[i]['guige'].length<=2
                          ?
                      Row(
                        children: [
                          GestureDetector(
                            child: Container(
                              decoration: new BoxDecoration(
                                //背景
                                color: Colors.white,
                                //设置四周圆角 角度
                                borderRadius: BorderRadius.all(Radius.circular(4.0)),
                                //设置四周边框
                                border: new Border.all(width: 1, color: Colors.orangeAccent),
                              ),
                              alignment: Alignment.center,
                              width: 15,
                              height: 20,
                              child: Center(
                                child: Text("-"),
                              ),
                              padding: EdgeInsets.fromLTRB(1, 0, 0, 1),
                            ),
                            onTap: () async {
                              if(userId==null || userId==""){
                                Fluttertoast.showToast(
                                    msg: "请先登录",
                                    toastLength: Toast.LENGTH_SHORT,
                                    gravity: ToastGravity.BOTTOM,
                                    timeInSecForIosWeb: 1,
                                    backgroundColor: Colors.black45,
                                    textColor: Colors.white,
                                    fontSize: 16.0
                                );
                                Future.delayed(Duration(seconds: 2), () {//延时2s跳转登录页面
                                });
                              }
                              if(zongjia > 0 && goodsList[i]['catNum'] > 0){
                                zongjia = zongjia-goodsList[i]['gprice']-goodsList[i]['gdabaofei'];
                                zongdabaofei = zongdabaofei-goodsList[i]['gdabaofei'];
                                zongjiage = zongjia.toStringAsFixed(2);
                                var x = await HttpUtil().get("/waimai/mShopCat/gaiNum?scatId=${goodsList[i]['catId']}&type=1");
                                if(x['code']==200){
                                  for(int j=0;j<cartList.length;j++){
                                    if(cartList[j]['userId']==userId && cartList[j]['mgid']==goodsList[i]['id']){
                                      cartList[j]['scatNum']--;
                                    }
                                    if(cartList[j]['scatNum']==0){
                                      cartList.removeAt(j);
                                    }
                                  }
                                  cartsize--;
                                  goodsList[i]['catNum']--;
                                  setState(() {});
                                }
                              }
                            },
                          ),
                          SizedBox(width: ScreenUtil().setWidth(4),),
                          // Text(goodsList[i]['catNum'].toString()),
                          Container(
                            width: 25,
                            child: Center(
                              child:Text(goodsList[i]['catNum'].toString(),style: TextStyle(fontSize: 14),),
                            ),
                          ),
                          SizedBox(width: ScreenUtil().setWidth(4),),
                          GestureDetector(
                            child: Container(
                              decoration: new BoxDecoration(
                                //背景
                                color: Colors.orangeAccent,
                                //设置四周圆角 角度
                                borderRadius: BorderRadius.all(Radius.circular(4.0)),
                                //设置四周边框
                                border: new Border.all(width: 1, color: Colors.orangeAccent),
                              ),
                              width: 15,
                              height: 20,
                              child: Center(
                                child: Text("+"),
                              ),
                              padding: EdgeInsets.fromLTRB(1, 0, 0, 1),
                            ),
                            onTap: () async {
                              if(userId==null || userId==""){
                                Fluttertoast.showToast(
                                    msg: "请先登录",
                                    toastLength: Toast.LENGTH_SHORT,
                                    gravity: ToastGravity.BOTTOM,
                                    timeInSecForIosWeb: 1,
                                    backgroundColor: Colors.black45,
                                    textColor: Colors.white,
                                    fontSize: 16.0
                                );
                                Future.delayed(Duration(seconds: 2), () {//延时2s跳转登录页面
                                });
                              }
                              print(goodsList[i]['kucun']);
                              print(goodsList[i]['catNum']);
                              if(goodsList[i]['kucun']<=goodsList[i]['catNum']){
                                Fluttertoast.showToast(
                                    msg: "库存不足",
                                    toastLength: Toast.LENGTH_SHORT,
                                    gravity: ToastGravity.BOTTOM,
                                    timeInSecForIosWeb: 1,
                                    backgroundColor: Colors.black45,
                                    textColor: Colors.white,
                                    fontSize: 16.0
                                );
                                return ;
                              }
                                zongjia = zongjia+goodsList[i]['gprice']+goodsList[i]['gdabaofei'];
                                zongdabaofei = zongdabaofei+goodsList[i]['gdabaofei'];
                                zongjiage = zongjia.toStringAsFixed(2);
                                //加入购物车
                                var x = await HttpUtil().get("/waimai/mShopCat/addMGoodscat?mgid=${goodsList[i]['id']}&userId=${userId}&catnum=1"+"&names=&params=&money="+goodsList[i]['gprice'].toString());
                                if(x['code']==200){
                                  if(goodsList[i]['catNum']>0){
                                    for(int j=0;j<cartList.length;j++){
                                      if(cartList[j]['userId']==userId && cartList[j]['mgid']==goodsList[i]['id']){
                                        cartList[j]['scatNum']++;
                                      }
                                    }
                                  }else{
                                    Map map={};
                                    map['userId']=userId;
                                    map['mgid']=goodsList[i]['id'];
                                    map['scatNum']=1;
                                    map['money']=goodsList[i]['gprice'];
                                    map['id']=x['data'];
                                    Map goodsmap={};
                                    goodsmap['gimages']=goodsList[i]['gimages'];
                                    goodsmap['guige']=goodsList[i]['guige'];
                                    goodsmap['gname']=goodsList[i]['gname'];
                                    goodsmap['gprice']=goodsList[i]['gprice'];
                                    map['mgoods']=goodsmap;
                                    cartList.add(map);
                                  }
                                  cartsize++;
                                  goodsList[i]['catId']=x['data'];
                                  goodsList[i]['catNum']++;
                                }
                                setState(() {});
                            },
                          )
                        ],
                      )
                          :
                      Row(
                            children: [
                              GestureDetector(
                                child: Container(
                                  decoration: new BoxDecoration(
                                    //背景
                                    color: Colors.orangeAccent,
                                    //设置四周圆角 角度
                                    borderRadius: BorderRadius.all(Radius.circular(4.0)),
                                    //设置四周边框
                                    border: new Border.all(width: 1, color: Colors.orangeAccent),
                                  ),
                                  width: 50,
                                  child: Center(
                                    child: Text("选规格",style: TextStyle(fontSize: 12),),
                                  ),
                                  padding: EdgeInsets.all(3),
                                ),onTap: () async {
                                  if(userId==null || userId==""){
                                    // Fluttertoast.showToast(msg: "请先登录");
                                    Fluttertoast.showToast(
                                        msg: "请先登录",
                                        toastLength: Toast.LENGTH_SHORT,
                                        gravity: ToastGravity.BOTTOM,
                                        timeInSecForIosWeb: 1,
                                        backgroundColor: Colors.black45,
                                        textColor: Colors.white,
                                        fontSize: 16.0
                                    );
                                    Future.delayed(Duration(seconds: 2), () {//延时2s跳转登录页面
                                    });
                                  }
                                  var guige = goodsList[i]['guige'];//商品规格
                                  int guigeNum=0;
                                  int guigekucun=goodsList[i]['kucun'];
                                  if(guige.length>2){
                                  params = []; //规格下标
                                  names = []; //选中的规格
                                  panduan = []; //判断规格是否选重复
                                  guigejia = goodsList[i]['gprice'];//初始化规格价格
                                  guigeList = json.decode(guige);//将规格转为数组
                                  showModalBottomSheet(
                                    context: context,
                                      shape: new RoundedRectangleBorder(
                                        borderRadius: BorderRadius.only(
                                            topLeft: Radius.circular(20.0),
                                            topRight: Radius.circular(20.0)),
                                      ),
                                    builder: (BuildContext context) {
                                      return StatefulBuilder(
                                          builder: (context,setDialogState){
                                            return Container(
                                              height:ScreenUtil().setHeight(600),
                                              margin: EdgeInsets.only(left: 10),
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: [
                                                  Text(goodsList[i]['gname'],style: TextStyle(fontSize:26),),
                                                  Row(
                                                    children: [
                                                      Text("￥",style: TextStyle(fontSize: 16,color: Colors.red),),
                                                      Text("$guigejia",style: TextStyle(fontSize: 20,color: Colors.deepOrange),),
                                                    ],
                                                  ),
                                                  Row(
                                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                    children: [
                                                      Text("数量",style: TextStyle(fontSize: 20),),
                                                      Row(
                                                        children: [
                                                          GestureDetector(
                                                            child: Container(
                                                              decoration: new BoxDecoration(
                                                                //背景
                                                                color: Colors.white,
                                                                //设置四周圆角 角度
                                                                borderRadius: BorderRadius.all(Radius.circular(4.0)),
                                                                //设置四周边框
                                                                border: new Border.all(width: 1, color: Colors.orangeAccent),
                                                              ),
                                                              alignment: Alignment.center,
                                                              width: 18,
                                                              height: 24,
                                                              child: Center(
                                                                child: Text("-"),
                                                              ),
                                                              padding: EdgeInsets.fromLTRB(1, 0, 0, 1),
                                                            ),
                                                            onTap: () async {
                                                              if(userId==null || userId==""){
                                                                Fluttertoast.showToast(
                                                                    msg: "请先登录",
                                                                    toastLength: Toast.LENGTH_SHORT,
                                                                    gravity: ToastGravity.BOTTOM,
                                                                    timeInSecForIosWeb: 1,
                                                                    backgroundColor: Colors.black45,
                                                                    textColor: Colors.white,
                                                                    fontSize: 16.0
                                                                );
                                                                Future.delayed(Duration(seconds: 2), () {//延时2s跳转登录页面
                                                                });
                                                              }
                                                              if(guigeNum>=1){
                                                                guigeNum--;
                                                                setDialogState((){ //底部弹窗更新

                                                                });
                                                              }
                                                            },
                                                          ),
                                                          SizedBox(width: ScreenUtil().setWidth(8),),
                                                          // Text(goodsList[i]['catNum'].toString()),
                                                          Container(
                                                            width: 25,
                                                            child: Center(
                                                              child:Text("$guigeNum",style: TextStyle(fontSize: 18),),
                                                            ),
                                                          ),
                                                          SizedBox(width: ScreenUtil().setWidth(8),),
                                                          GestureDetector(
                                                            child: Container(
                                                              decoration: new BoxDecoration(
                                                                //背景
                                                                color: Colors.orangeAccent,
                                                                //设置四周圆角 角度
                                                                borderRadius: BorderRadius.all(Radius.circular(4.0)),
                                                                //设置四周边框
                                                                border: new Border.all(width: 1, color: Colors.orangeAccent),
                                                              ),
                                                              width: 18,
                                                              height: 24,
                                                              child: Center(
                                                                child: Text("+"),
                                                              ),
                                                              padding: EdgeInsets.fromLTRB(1, 0, 0, 1),
                                                            ),
                                                            onTap: () async {
                                                              if(userId==null || userId==""){
                                                                Fluttertoast.showToast(
                                                                    msg: "请先登录",
                                                                    toastLength: Toast.LENGTH_SHORT,
                                                                    gravity: ToastGravity.BOTTOM,
                                                                    timeInSecForIosWeb: 1,
                                                                    backgroundColor: Colors.black45,
                                                                    textColor: Colors.white,
                                                                    fontSize: 16.0
                                                                );
                                                                Future.delayed(Duration(seconds: 2), () {//延时2s跳转登录页面
                                                                });
                                                              }
                                                              if(guigekucun<=guigeNum){
                                                                Fluttertoast.showToast(
                                                                    msg: "库存不足",
                                                                    toastLength: Toast.LENGTH_SHORT,
                                                                    gravity: ToastGravity.BOTTOM,
                                                                    timeInSecForIosWeb: 1,
                                                                    backgroundColor: Colors.black45,
                                                                    textColor: Colors.white,
                                                                    fontSize: 16.0
                                                                );
                                                                return ;
                                                              }
                                                              guigeNum++;
                                                              setDialogState((){ //底部弹窗更新

                                                              });
                                                            },
                                                          )
                                                        ],
                                                      )
                                                    ],
                                                  ),
                                                  Expanded(
                                                    child:SingleChildScrollView(
                                                      child: new ListBody(
                                                        children: <Widget>[
                                                          _showGuigeDetail(guigeList,),
                                                        ],
                                                      ),
                                                    ),
                                                  ),
                                                  GestureDetector(
                                                    child: Container(
                                                      margin: EdgeInsets.symmetric(horizontal: 10,vertical: 5),
                                                      padding: EdgeInsets.symmetric(vertical: 5),
                                                      decoration:  new BoxDecoration(
                                                        //背景
                                                        color: Colors.yellow,
                                                        //设置四周圆角 角度
                                                        borderRadius: BorderRadius.all(Radius.circular(20)),
                                                        //设置四周边框
                                                        border: new Border.all(width: 2, color: Colors.yellow),
                                                      ),
                                                      child: Center(
                                                        child: Container(
                                                          width: ScreenUtil().setWidth(450),
                                                          margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
                                                          child: Row(
                                                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                                                            children: [
                                                              Text("加入购物车")
                                                            ],),
                                                        ),
                                                      ),
                                                    ),onTap: () async {
                                                    int n = guigeList.length;
                                                    int m = names.length;
                                                    if (m < n) {
                                                      Fluttertoast.showToast(msg: "请选择完整规格");
                                                      return;
                                                    }
                                                    if(guigeNum<=0){
                                                      Fluttertoast.showToast(
                                                          msg: "数量必须大于0",
                                                          toastLength: Toast.LENGTH_SHORT,
                                                          gravity: ToastGravity.BOTTOM,
                                                          timeInSecForIosWeb: 1,
                                                          backgroundColor: Colors.black45,
                                                          textColor: Colors.white,
                                                          fontSize: 16.0
                                                      );
                                                      return;
                                                    }
                                                    // params = params.sublist(params.length - n);
                                                    // names = names.sublist(names.length - n);
                                                    if (m > 1) {
                                                      //排序
                                                      for (int i = 0;i < n;i++) {
                                                        if (guigeList[i]['name'] != panduan[i]) {
                                                          for (int e = 0; e < panduan.length; e++) {
                                                            if (guigeList[i]['name'] == panduan[e]) {
                                                              var z = panduan[i];
                                                              panduan[i] = panduan[e];
                                                              panduan[e] = z;
                                                              var y = names[i];
                                                              names[i] = names[e];
                                                              names[e] = y;
                                                              var o = params[i];
                                                              params[i] = params[e];
                                                              params[e] = o;
                                                            }
                                                          }
                                                        }
                                                      }
                                                    }
                                                    guiges = json.encode(names);
                                                    guigexiabiao = json.encode(params);
                                                    zongjia = zongjia+guigejia+goodsList[i]['gdabaofei'];
                                                    zongdabaofei = zongdabaofei+goodsList[i]['gdabaofei'];
                                                    zongjiage = zongjia.toStringAsFixed(2);
                                                    //加入购物车
                                                    var x = await HttpUtil().get("/waimai/mShopCat/addMGoodscat?mgid=${goodsList[i]['id']}&userId=${userId}&catnum="+guigeNum.toString()+"&names="+guiges+"&params="+guigexiabiao+"&money="+goodsList[i]['gprice'].toString());
                                                    if(x['code']==200){
                                                      int xb=0;
                                                      cartsize+=guigeNum;
                                                      goodsList[i]['catId']=x['data'];
                                                      goodsList[i]['catNum']++;
                                                      for(int f=0;f<cartList.length;f++,xb++){
                                                        if(goodsList[i]['id']==cartList[f]['mgid'] && guiges==cartList[f]['guiges'] && guigexiabiao==cartList[f]['guigeparams']){
                                                          cartList[f]['scatNum']+=guigeNum;
                                                          break;
                                                        }
                                                      }
                                                      if(xb==cartList.length){
                                                        Map map={};
                                                        map['userId']=userId;
                                                        map['mgid']=goodsList[i]['id'];
                                                        map['scatNum']=guigeNum;
                                                        map['money']=goodsList[i]['gprice'];
                                                        map['id']=x['data'];
                                                        map['guiges']=guiges;
                                                        map['guigeparams']=guigexiabiao;
                                                        Map goodsmap={};
                                                        goodsmap['gimages']=goodsList[i]['gimages'];
                                                        goodsmap['guige']=goodsList[i]['guige'];
                                                        goodsmap['gname']=goodsList[i]['gname'];
                                                        goodsmap['gprice']=goodsList[i]['gprice'];
                                                        map['mgoods']=goodsmap;
                                                        cartList.add(map);
                                                      }
                                                    }
                                                    setState(() {});
                                                    if (x['code'] == 200) {
                                                      Fluttertoast.showToast(msg: "加入购物车成功");
                                                    } else {
                                                      Fluttertoast.showToast(msg: x['msg']);
                                                    }
                                                    Navigator.pop(context); // 隐藏底部规格选择
                                                    // Navigator.of(context).pop();
                                                  },
                                                  )
                                                ],
                                              ),
                                            );
                                          }
                                      );
                                    },
                                  ).then((val) {
                                  });
                                }
                              },
                              )
                            ],
                          )
                    ],
                  )
                ],
              )
            ],
          ) ,
        ) ,
        onTap: () async {
            //点击商品跳商品详情页面
            Map value= await MyRoute.push(GoodsDetail(gid: goodsList[i]['id'],goodsShop: goodsList[i],cartList: cartList,cartSize: cartsize,merchantName: merchantName,merchantId: merchantId,goodsTypeList: goodsTypeList,zongjia: zongjia,zongdabaofei: zongdabaofei,));
            if(value==null){
              MyRoute.pop();
            }
            cartList=value['cartList'];
            goodsTypeList=value['goodsTypeList'];
            cartsize=value['cartSize'];
            zongjia=value['zongjia'];
            zongdabaofei=value['zongdabaofei'];
            zongjiage=zongjia.toStringAsFixed(2);
            setState(() {

            });
          },
      ),
      );
    }
    return Container(
      child: Column(children: x),
    );
  }

  // 循环显示规格界面中的参数
  Widget _showGuigeDetail(guige) {
    List<Widget> col = [];
    for (var i = 0; i < guige.length; i++) {
      List<String> x = [];
      var values = guige[i]['value'].split('-');
      for (var j = 0; j < values.length; j++) {
        x.add(values[j].toString());
      }
      col.add(Align(
        child: Text(guige[i]['name']),
        alignment: Alignment.topLeft,
      )); // 规格名称
      col.add(GroupButton(
        isRadio: true,
        spacing: 10,
        borderRadius: BorderRadius.all(Radius.circular(5)),
        onSelected: (index, isSelected) {
          int n = -1;
          if (panduan.contains(guige[i]['name'])) {
            for (var x = 0; x < names.length; x++) {
              var ttt = names[x][guige[i]['name']];
              if (ttt != null && ttt != "") {
                n = x;
                break;
              }
            }
          }
          int xiabiao = int.parse('$index');
          if (n == -1) {
            panduan.add(guige[i]['name']);
            params.add(xiabiao);
            names.add({guige[i]['name']: values[xiabiao]});
          } else {
            params[n] = xiabiao;
            names[n][guige[i]['name']] = values[xiabiao];
          }
          // 此处更新显示的规格价格
          funCb(() {});
        },
        buttons: x));
    }
    return StatefulBuilder(builder: (context1, setBottomSheetState) {
      funCb = setBottomSheetState;
      return Container(
        child: Column(children: col),
      );
    });
  }
}